package example.hello;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.security.SecureRandom;

public class Client implements Observer {
	private Hello observeState;
	private String clientID;
	
	public Client(Hello server, String id) {
		observeState = server;
		clientID = id;
	}
	
	public static void main(String[] args) {
		if (args.length < 2) {
			System.err.println("Syntax: Client host clientID");
			return;
		}
		String host = (args.length < 1) ? null : args[0];
		
		String id = args[1];
		
		try {
			Registry registry = LocateRegistry.getRegistry(host);
			Hello stub = (Hello) registry.lookup("HelloObserver");
			
			Client client = new Client(stub, id);
			
			SecureRandom rand = new SecureRandom();
			
			try {
				UnicastRemoteObject.exportObject(client, rand.nextInt(10000) + 10000);
				stub.subcribe(client);
			} catch (Exception e) {
				System.err.println("Client exception: " + e.toString());
				e.printStackTrace();
			}
			
			
			//String response = stub.sayHello();
			//System.out.println("response: " + response);			
			while (true) {
				try {
					stub.setData("update from client " + id);
					Thread.sleep(500);					
					client.update();
				} catch (Exception e) {
					System.err.println(e.toString());
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			System.err.println("Client exception: " + e.toString());
			e.printStackTrace();
		}
		
		
	}
	
	public void update() throws RemoteException {
		try {
			String data = observeState.getData();
			System.err.println("From " + clientID + ": " + data);
		} catch (Exception e) {
			System.err.println("Client exception: " + e.toString());
			e.printStackTrace();
		}
	}
	
	public String getName() throws RemoteException {
		return clientID;
	}
}
